"""
用户界面模块
实现日历主界面展示
"""
import tkinter as tk
from tkinter import ttk, font
from PIL import Image, ImageTk
from calendar_core import CalendarCore
from festival_data import FestivalData

class CalendarUI:
    def __init__(self, master):
        self.master = master
        self.core = CalendarCore()
        self.festival_data = FestivalData()

        self.setup_ui()
        self.update_calendar()

    def setup_ui(self):
        """初始化UI界面"""
        self.master.title("万年历")
        self.master.geometry("800x600")

        # 设置背景
        self.bg_image = Image.open("assets/bg_images/main_bg.jpg")
        self.bg_photo = ImageTk.PhotoImage(self.bg_image)
        self.bg_label = tk.Label(self.master, image=self.bg_photo)
        self.bg_label.place(x=0, y=0, relwidth=1, relheight=1)

        # 顶部控制栏
        self.control_frame = tk.Frame(self.master, bg="#f0f0f0")
        self.control_frame.pack(fill=tk.X, padx=10, pady=10)

        # 年月选择
        self.year_var = tk.IntVar()
        self.month_var = tk.IntVar()

        tk.Label(self.control_frame, text="年:", bg="#f0f0f0").pack(side=tk.LEFT)
        self.year_spin = tk.Spinbox(self.control_frame, from_=1900, to=2100,
                                   textvariable=self.year_var, width=5)
        self.year_spin.pack(side=tk.LEFT)

        tk.Label(self.control_frame, text="月:", bg="#f0f0f0").pack(side=tk.LEFT, padx=(10,0))
        self.month_spin = tk.Spinbox(self.control_frame, from_=1, to=12,
                                    textvariable=self.month_var, width=3)
        self.month_spin.pack(side=tk.LEFT)

        # 切换按钮
        self.update_btn = tk.Button(self.control_frame, text="更新",
                                  command=self.update_calendar)
        self.update_btn.pack(side=tk.LEFT, padx=10)

        # 当前时间显示
        self.time_label = tk.Label(self.control_frame, text="", bg="#f0f0f0")
        self.time_label.pack(side=tk.RIGHT)

        # 日历显示区域
        self.calendar_frame = tk.Frame(self.master, bg="white")
        self.calendar_frame.pack(fill=tk.BOTH, expand=True, padx=10, pady=(0,10))

    def update_calendar(self):
        """更新日历显示"""
        current_date = self.core.get_current_date()
        self.year_var.set(current_date.year)
        self.month_var.set(current_date.month)

        # 更新当前时间
        self.update_time()

        # 清空日历区域
        for widget in self.calendar_frame.winfo_children():
            widget.destroy()

        # 创建日历表头 (星期)
        weekdays = ["日", "一", "二", "三", "四", "五", "六"]
        for i, day in enumerate(weekdays):
            label = tk.Label(self.calendar_frame, text=day,
                            font=("Arial", 12, "bold"), bg="white")
            label.grid(row=0, column=i, sticky="nsew", padx=2, pady=2)

        # 计算当月天数及第一天是星期几
        year = self.year_var.get()
        month = self.month_var.get()
        days_in_month = self.core.get_month_days(year, month)
        first_day = self.core.get_weekday(year, month, 1)

        # 显示日期
        row = 1
        col = first_day
        for day in range(1, days_in_month + 1):
            lunar_date = self.core.get_lunar_date(year, month, day)
            festival = self.festival_data.get_festival(year, month, day, lunar_date)

            # 检查是否是当前日期
            is_today = (year == current_date.year and
                       month == current_date.month and
                       day == current_date.day)

            # 设置今日特殊样式
            day_frame = tk.Frame(self.calendar_frame, bd=1, relief=tk.RIDGE,
                                bg="#e6f7ff" if is_today else "white")
            day_frame.grid(row=row, column=col, sticky="nsew", padx=2, pady=2)

            # 阳历日期
            solar_label = tk.Label(day_frame, text=str(day),
                                 font=("Arial", 10, "bold"),
                                 bg="#e6f7ff" if is_today else "white")
            solar_label.pack(anchor=tk.NW)

            # 农历日期
            lunar_label = tk.Label(day_frame, text=lunar_date.chinese(),
                                 font=("Arial", 8),
                                 bg="#e6f7ff" if is_today else "white")
            lunar_label.pack()

            # 节日/节气
            if festival:
                festival_label = tk.Label(day_frame, text=festival,
                                        font=("Arial", 8), fg="red",
                                        bg="#e6f7ff" if is_today else "white")
                festival_label.pack()

            # 绑定点击事件
            day_frame.bind("<Button-1>", lambda e, d=day: self.show_day_detail(d))

            col += 1
            if col > 6:
                col = 0
                row += 1

        # 设置网格权重
        for i in range(7):
            self.calendar_frame.grid_columnconfigure(i, weight=1)
        for i in range(row + 1):
            self.calendar_frame.grid_rowconfigure(i, weight=1)

    def update_time(self):
        """更新当前时间显示"""
        current_time = self.core.get_current_date().strftime("%Y-%m-%d %H:%M:%S")
        self.time_label.config(text=f"当前时间: {current_time}")
        self.master.after(1000, self.update_time)

    def show_day_detail(self, day):
        """显示日期详情弹窗"""
        year = self.year_var.get()
        month = self.month_var.get()
        lunar_date = self.core.get_lunar_date(year, month, day)
        festival = self.festival_data.get_festival(year, month, day, lunar_date)

        # 创建弹窗
        from popup_window import DayDetailPopup
        detail_popup = DayDetailPopup(self.master, year, month, day, lunar_date, festival)
